package ch04;

import edu.princeton.cs.algs4.LinkedQueue;

import java.util.ArrayList;
import java.util.List;

public class EdgeWeightGraph {
    private final int V;
    private int E;
    private List<Edge>[] adj;

    public EdgeWeightGraph(int V) {
        this.V = V;
        E = 0;
        adj = new ArrayList[V];
        for (int i = 0; i < V; i++) {
            adj[i] = new ArrayList<>();
        }
    }

    public int getV() {
        return V;
    }

    public int getE() {
        return E;
    }


    public void addEdge(Edge edge) {
        int v = edge.either();
        int w = edge.other(v);
        adj[v].add(edge);
        adj[w].add(edge);
        E++;
    }

    public Iterable<Edge> adj(int t) {
        return adj[t];
    }

    public Iterable<Edge> edges() {
        LinkedQueue<Edge> queue = new LinkedQueue<>();
        for (int i = 0; i < V; i++) {
            for (Edge edge : adj[i]) {
                if (i < edge.other(i)) {
                    queue.enqueue(edge);
                }
            }
        }
        return queue;
    }

    public static EdgeWeightGraph getGraph() {

        EdgeWeightGraph edgeWeightGraph = new EdgeWeightGraph(10);

        Edge edge = new Edge(1,2,5.2);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(3,2,5.34);

        edgeWeightGraph.addEdge(edge);
        edge = new Edge(6,1,9);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(4,5,4.5);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(5,2,2);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(8,4,1.5);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(9,1,5);
        edge = new Edge(1,9,5);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(3,9,4);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(0,1,7.8);
        edgeWeightGraph.addEdge(edge);
        edge = new Edge(7,2,7.8);
        edgeWeightGraph.addEdge(edge);

        return edgeWeightGraph;
    }

    public static void main(String[] args) {
        EdgeWeightGraph graph = EdgeWeightGraph.getGraph();
        for (Edge edge : graph.edges()) {
            System.out.println(edge);
        }
    }
}
